import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Row, Col, Button } from 'antd';
import EditPage from '@/components/EditPage';
import AntdForm from '@/components/AntdForm';
import AntdFormItem from '@/components/AntdFormItem';
import AdButton from '@/components/AdButton';
import AntdSelectRegion from '@/components/AntdSelectRegion';
import AntdInput from '@/components/AntdInput';
import { editCol, editGutter, editRow } from '@/utils/constans';
import { codes } from './utils';

@connect(({ addressLib }) => ({ addressLibDetail: addressLib.addressLibDetail }))
@Form.create()
export default class AddressLibOperate extends Component {
  state = {
    detailId: '',
    disabled: false,
  };

  componentDidMount() {
    const {
      match: {
        params: { id },
      },
      addressLibDetail,
      dispatch,
    } = this.props;
    if (!id) return;
    this.setState({ detailId: id });
    if (addressLibDetail[id]) return;
    dispatch({
      type: 'addressLib/addressLibDetail',
      payload: { id },
    });
  }

  /**
   * 保存数据
   */
  saveInfo = () => {
    const { form, dispatch } = this.props;
    const { detailId } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      const { distributionId, ...value } = values;
      value.distributionId = distributionId[distributionId.length - 1];
      if (detailId !== '') {
        value.id = detailId;
      }
      dispatch({
        type: 'addressLib/addressLibOperate',
        payload: value,
        callback: data => {
          this.setState(preState => ({
            disabled: !preState.disabled,
          }));
        },
      });
    });
  };

  columns = [
    {
      title: '地址全路径',
      dataIndex: 'fullName',
      width: '50%',
    },
    {
      title: '关键字',
      dataIndex: 'keyWords',
      width: '50%',
    },
  ];
  headerOperate = () => {
    const { disabled, detailId } = this.state;
    return disabled ? (
      <AdButton
        type="primary"
        onClick={() => {
          this.setState(preState => ({
            disabled: !preState.disabled,
          }));
        }}
        text="编辑"
      />
    ) : (
      <Button.Group>
        <AdButton type="primary" onClick={e => this.saveInfo(e)} text="保存" />
        {detailId && (
          <AdButton
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="取消"
          />
        )}
      </Button.Group>
    );
  };
  render() {
    const { detailId, disabled } = this.state;
    const {
      form: { getFieldDecorator },
      addressLibDetail,
    } = this.props;
    const detail = addressLibDetail[detailId];
    const editPageParams = {
      title: detailId ? '编辑地址库' : '新增地址库',
      headerOperate: this.headerOperate(),
      panelTitle: ['基础信息'],
      code: detailId ? codes.edit : codes.add,
    };
    const commonParams = {
      getFieldDecorator,
    };
    const formItem = [
      [
        <AntdFormItem
          label="地址"
          code="address"
          initialValue={detail ? detail.address : undefined}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label="配送区域"
          code="distributionId"
          initialValue={detail ? detail.allParentIds : undefined}
          {...commonParams}
        >
          <AntdSelectRegion
            url="mds/mds-address-lib/selectMdsDistList"
            paramsLabel="id"
            label="name"
            filter={false}
            disabled={disabled}
            split="/"
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="纬度"
          code="latitude"
          initialValue={detail ? detail.latitude : undefined}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label="经度"
          code="longitude"
          initialValue={detail ? detail.longitude : undefined}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
      ],
    ];

    return (
      <EditPage {...editPageParams}>
        <AntdForm>
          {formItem.map((item, index) => {
            return (
              <Row gutter={editGutter} key={index}>
                {item.map((v, i) => {
                  const colSpan = item.length === 1 ? editRow : editCol;
                  return (
                    <Col {...colSpan} key={index + i}>
                      {v}
                    </Col>
                  );
                })}
              </Row>
            );
          })}
        </AntdForm>
      </EditPage>
    );
  }
}
